import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.swing.JFileChooser;

public class FileUtils {
	private File file;

	public JFileChooser selectFile() {
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setCurrentDirectory(new File(".\\files"));
		fileChooser.setDialogTitle("Choose a file");
		fileChooser.setVisible(true);
		return fileChooser;
	}

	public boolean saveFile(Signal sign) throws IOException {
		/* select where save */
		JFileChooser fileChooser = new JFileChooser();
		fileChooser.setDialogTitle("Choose a file");
		fileChooser.setVisible(true);
		fileChooser.setCurrentDirectory(new File(".\\files"));
		fileChooser.setMultiSelectionEnabled(false);
		int returnValue = fileChooser.showOpenDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION) {
			file = fileChooser.getSelectedFile();
			SaveConfig sc = new SaveConfig(sign, file);
			sc.setVisible(true);
		}
		/*
		 * create byte array output stream ByteArrayOutputStream bytestream =
		 * new ByteArrayOutputStream(); DataOutputStream datastream = new
		 * DataOutputStream(bytestream); /* write signal parameters
		 */
		/*
		 * datastream.writeShort(sign.getT0());
		 * datastream.writeShort(sign.getF());
		 * datastream.writeByte(sign.getFlag());
		 * datastream.writeInt(sign.getSamples()); for (double d :
		 * sign.getContent()) { datastream.writeDouble(d); }
		 * datastream.writeShort(sign.getT0()); datastream.flush(); /* convert
		 * to byte array and write to file
		 * 
		 * byte[] bytes = bytestream.toByteArray(); FileOutputStream
		 * fileoutputstream = new FileOutputStream(file); for (int i = 0; i <
		 * bytes.length; i++) { fileoutputstream.write(bytes[i]); }
		 * fileoutputstream.close(); return true;
		 */
		return true;
	}

	public boolean readFile() {
		return true;
	}

	public boolean writeFile() {
		return true;
	}

	public static byte[] getBytesFromFile(File file) throws IOException {
		InputStream is = new FileInputStream(file);

		long length = file.length();

		if (length > Integer.MAX_VALUE) {

		}

		// Create the byte array to hold the data
		byte[] bytes = new byte[(int) length];

		// Read in the bytes
		int offset = 0;
		int numRead = 0;
		while (offset < bytes.length
				&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
			offset += numRead;
		}

		// Ensure all the bytes have been read in
		if (offset < bytes.length) {
			throw new IOException("Could not completely read file "
					+ file.getName());
		}

		// Close the input stream and return bytes
		is.close();
		return bytes;
	}
}
